<template>
  <div class="login">
    <el-form status-icon :model="ruleForm2" ref="ruleForm" :rules="rules" class="login-ruleForm">
      <h1 class="login-h1">客户管理系统</h1>
      <el-form-item prop="username">
        <p class="label">账号</p>
        <el-input class="el_input" v-model="ruleForm2.username"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <p class="label">密码</p>
        <el-input type="password" v-model="ruleForm2.password" class="el_input" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit" class="btn-login">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
export default {
  components: {},
  data() {
    return {
      ruleForm2: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 20, message: "超出长度", trigger: "blur" }
        ],
        password: [{ validator: this.validaPwd, trigger: "blur" }]
      }
    };
  },
  methods: {
    validaPwd(rule, value, cb) {
      console.log(rule);
      if (!value) {
        cb("密码为空");
      } else {
        cb();
      }
    },
    submit() {
      this.$refs.ruleForm.validate(cb => {
        if (cb) {
          console.log("表单收集完成");
          const requests = {
            username: this.ruleForm2.username,
            password: this.ruleForm2.password
          };
          axios.post("/tokens", qs.stringify(requests)).then(res => {
            if (res.data.success) {
              console.log(res.data);
              
              localStorage.setItem("token", res.data.data);
              localStorage.setItem("username", this.ruleForm2.username);
              alert("登录成功");
              this.$router.push("/");
            } else {
              this.$message.error('错了哦，这是一条错误消息');
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.login-h1 {
  color: #fff;
  position: relative;
  font-weight: bold;
  margin-left: 100px;
}
.login {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #324057;
  .login-ruleForm {
    height: 200px;
    width: 400px;
    .label {
      color: #fff;
      display: inline-block;
      margin-right: 10px;
    }
    .el_input {
      display: inline-block;
      width: 90%;
    }
    .btn-login {
      width: 90%;
      margin-left: 40px;
    }
  }
}
</style>